package com.deer.wms.ASN.manage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.ASN.manage.constant.AsnManageConstant;
import com.deer.wms.ASN.manage.dao.AsnDetailMapper;
import com.deer.wms.ASN.manage.dao.AsnMasterMapper;
import com.deer.wms.ASN.manage.model.AcceptLog;
import com.deer.wms.ASN.manage.model.Lines;
import com.deer.wms.ASN.manage.model.MiscellaneousVo;
import com.deer.wms.ASN.manage.model.asn.*;
import com.deer.wms.ASN.manage.model.asn.CreateASN.CreateASN;
import com.deer.wms.ASN.manage.model.asn.CreateASN.CreateASNSKUDetail;
import com.deer.wms.ASN.manage.model.asn.CreateASN.CreateASNShipDetail;
import com.deer.wms.ASN.manage.model.buy.RequestBuyDetail;
import com.deer.wms.ASN.manage.model.file.AsnDetailFile;
import com.deer.wms.ASN.manage.model.file.AsnMasterFile;
import com.deer.wms.ASN.manage.service.*;
import com.deer.wms.base.system.dao.*;
import com.deer.wms.base.system.model.*;
import com.deer.wms.base.system.model.Area.AreaInfo;
import com.deer.wms.base.system.model.Cell.CellInfo;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.model.Shelf.ShelfInfo;
import com.deer.wms.base.system.model.Supplier.SupplierManage;
import com.deer.wms.base.system.model.erp.ErpInConstant;
import com.deer.wms.base.system.model.erp.ErpTask;
import com.deer.wms.base.system.model.erp.outSourceBillNo;
import com.deer.wms.base.system.service.CellInfoService;
import com.deer.wms.base.system.service.ErpService;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.base.system.service.SupplierManageService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.dao.InventoryMapper;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.text.Convert;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.BeanUtils;
import com.deer.wms.project.root.util.CollectionUtils;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.project.root.util.StringUtils;
import com.deer.wms.review.manage.model.BillRecord;
import com.deer.wms.review.manage.service.BillRecordService;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.constant.SystemManageConstant;
import com.deer.wms.system.manage.model.DataDictDetail;
import com.deer.wms.system.manage.model.organization.Organization;
import com.deer.wms.system.manage.model.ware.WareInfo;
import com.deer.wms.system.manage.service.*;
import com.deer.wms.ware.task.model.SO.SoDetail;
import com.deer.wms.ware.task.service.PushErpService;
import com.deer.wms.ware.task.service.SoMasterService;
import com.deer.wms.ware.task.service.impl.SoDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * Created by guo on 2020/01/03.
 */
@Service
@Transactional
public class AsnMasterServiceImpl extends SuperServiceImpl<AsnMasterMapper, AsnMaster> implements AsnMasterService {

    @Autowired
    private AsnMasterMapper asnMasterMapper;

    @Autowired
    private AsnMasterService asnMasterService;

    @Autowired
    private AsnDetailService asnDetailService;

    @Autowired
    private CaseMasterService caseMasterService;

    @Autowired
    private RequestBuyDetailService requestBuyDetailService;

    @Autowired
    private AsnMasterFileService asnMasterFileService;

    @Autowired
    private AsnDetailFileService asnDetailFileService;

    @Autowired
    private ValidatorService validatorService;

    @Autowired
    private BillRecordService billRecordService;

    @Autowired
    private WareInfoService wareInfoService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private AsnShipDetailService asnShipDetailService;

    @Autowired
    private ItemInfoService itemInfoService;

    @Autowired
    private AsnDetailMapper asnDetailMapper;

    @Autowired
    private SupplierManageMapper supplierManageMapper;

    @Autowired
    private PackDetailMapper packDetailMapper;
    @Autowired
    private PushErpService pushErpService;

    @Autowired
    private AcceptRecordService acceptRecordService;
    @Autowired
    private SoMasterService soMasterService;
    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private ErpBackRecordMapper erpBackRecordMapper;
    @Autowired
    private CellInfoService cellInfoService;
    @Autowired
    private ShelfInfoMapper shelfInfoMapper;
    @Autowired
    private AreaInfoMapper areaInfoMapper;

    @Autowired
    private CodeRuleService codeRuleService;

    @Autowired
    private AcceptLogService acceptLogService;
    @Autowired
    private SoDetailServiceImpl soDetailService;
    @Autowired
    private DataDictDetailService dataDictDetailService;

    @Override
    public void deleteByBillNo(String billNo) {
        asnMasterMapper.deleteByBillNo(billNo);
    }

    @Override
    public void deleteByRequestBuyNo(String requestBuyBillNo){
        asnMasterMapper.deleteByRequestBuyNo(requestBuyBillNo);

    }

    @Override
    public void closeById(Integer id) {
        AsnMaster asnMaster = asnMasterService.getById(id);
        asnMaster.setAsnState(AsnManageConstant.ASN_STATE_CLOSE);
        List<AsnDetail> asnDetails = asnDetailService.getListByField("bill_no", asnMaster.getBillNo());
        for (AsnDetail asnDetail : asnDetails) {
            if (ObjectUtil.equal(AsnManageConstant.ASN_STATE_INIT, asnDetail.getState()) || ObjectUtil.equal(AsnManageConstant.ASN_STATE_PARTED, asnDetail.getState())) {
                asnDetail.setState(AsnManageConstant.ASN_STATE_CLOSE);
            }
        }
        asnMasterService.updateById(asnMaster);
        asnDetailService.updateBatchById(asnDetails);
    }

    @Override
    public List<AsnMasterDto> findList(AsnMasterCriteria criteria) {
        return asnMasterMapper.findList(criteria);
    }

    @Override
    public List<AsnMasterDto> findPdaList(AsnMasterCriteria criteria) {
        return asnMasterMapper.findPdaList(criteria);
    }


    @Autowired
    private SupplierManageService supplierManageService;

    @Override
    public void createAsnMaster(AsnData asnData, CurrentUser currentUser){
        AsnMaster asnMaster = asnData.getAsnMaster();
        String tableName = "asn_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo = "ZS"+"-"+nextId;
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        //0-等待审核 1-审核通过 -1-审核退回
        Integer state = 2;
        //调拨生成
        if(asnData.getBillSource()==4){
            BillRecord billRecord2 =billRecordService.findByBillNoAndType(asnMaster.getAllotBillNo(),41);//生成ASN

            billRecordService.updateBillRecord(billRecord2,currentUser);
        }
        //采购生成
        if(asnData.getBillSource()==0 ||asnData.getBillSource()==2 ){
            BillRecord billRecord2 =billRecordService.findByBillNoAndType(asnMaster.getRequestBuyBillNo(),10);//生成ASN
            billRecordService.updateBillRecord(billRecord2,currentUser);
        }

        //新增Master
        asnMaster.setCreateUserId(createUserId);
        asnMaster.setCreateUserName(createUserName);
        asnMaster.setState(state);
        asnMaster.setInsertType(asnData.getInsertType());
        asnMaster.setBillSource(asnData.getBillSource());
        if (ObjectUtil.isNotNull(asnMaster.getSupplierId())) {
            SupplierManage supplierManage = supplierManageService.getById(asnMaster.getSupplierId());
            asnMaster.setSupplierCode(supplierManage.getSupplierCode());
            asnMaster.setSupplierName(supplierManage.getSupplierName());
        }

        if (StringUtils.isNotEmpty(asnMaster.getBillNo())) {
            asnMasterService.updateById(asnMaster);
        } else {
            asnMaster.setBillNo(billNo);
            asnMasterService.save(asnMaster);
        }


        //新增detail
        List<AsnDetail> asnDetails = asnData.getAsnDetails();
        for (int i = 0; i < asnDetails.size(); i++) {
            String detailNo = billNo + "-" + (i + 1);
            AsnDetail asnDetail = asnDetails.get(i);
            asnDetail.setBillNo(billNo);
            asnDetail.setId(null);
            asnDetail.setDetailNo(detailNo);
            asnDetailService.save(asnDetail);
            //更新采购单的ASN数量
            String requestDetailDetailNo = asnDetail.getRequestDetailDetailNo();
            RequestBuyDetail requestBuyDetail = requestBuyDetailService.findByDetailNo(requestDetailDetailNo);
            if (requestBuyDetail != null) {
                requestBuyDetail.setAsnQuantity(asnDetail.getExpectQuantity() + requestBuyDetail.getAsnQuantity());
                requestBuyDetailService.updateById(requestBuyDetail);
            }
        }

        //送货单 跟TMS相关
//        List<AsnShipDetail> asnShipDetails = asnData.getAsnShipDetails();
//        if (asnShipDetails != null && asnShipDetails.size() > 0) {
//            for (AsnShipDetail asnShipDetail : asnShipDetails) {
//                asnShipDetail.setBillNo(billNo);
//                asnShipDetail.setCreateTime(DateUtils.getNowDateTimeString());
//                asnShipDetailService.save(asnShipDetail);
//            }
//        }
    }


    /**
     * 归档
     * @param billNo
     * @param currentUser
     */
    @Override
    public void createFile(String billNo, CurrentUser currentUser){
        AsnMaster asnMaster = asnMasterService.findBy("bill_no",billNo);
        //状态为 ASN完成状态
        if(asnMaster.getAsnState() !=3){
            throw new ServiceException(CommonCode.ASN_FILE_ERROR);
        }
        Integer fileUserId = currentUser.getUserId();
        String fileUserName = currentUser.getUserName();
        String fileTime = DateUtils.getNowDateTimeString();

        BillRecord billRecord =new BillRecord();
        billRecord.setBillNo(billNo);
        billRecord.setRecordType(6);//ASN归档
        billRecord.setCreateTime(fileTime);
        billRecord.setCreateUserId(fileUserId);
        billRecord.setCreateUserName(fileUserName);
        billRecordService.save(billRecord);
        AsnMasterFile asnMasterFile = new AsnMasterFile();
        BeanUtils.copyProperties(asnMaster, asnMasterFile);

        asnMasterFile.setFileUserId(fileUserId);
        asnMasterFile.setFileUserName(fileUserName);
        asnMasterFile.setFileTime(fileTime);
        asnMasterFileService.save(asnMasterFile);
        List<AsnDetail> asnDetails = asnDetailService.findByBillNo(billNo);

//        BeanUtils.copyProperties(asnDetails, asnDetailFile);
        for(int i=0;i<asnDetails.size();i++){
            AsnDetailFile asnDetailFile = new AsnDetailFile();
            asnDetailFile.setBillNo(asnDetails.get(i).getBillNo());
            asnDetailFile.setRequestDetailDetailNo(asnDetails.get(i).getRequestDetailDetailNo());
            asnDetailFile.setDetailNo(asnDetails.get(i).getDetailNo());
            asnDetailFile.setItemCode(asnDetails.get(i).getItemCode());
            asnDetailFile.setItemName(asnDetails.get(i).getItemName());
            asnDetailFile.setPackDetailId(asnDetails.get(i).getPackDetailId());
            asnDetailFile.setPackDescribe(asnDetails.get(i).getPackDescribe());
            asnDetailFile.setAcceptQuantity(asnDetails.get(i).getAcceptQuantity());
            asnDetailFile.setExpectQuantity(asnDetails.get(i).getExpectQuantity());
            asnDetailFile.setMemo(asnDetails.get(i).getMemo());
            asnDetailFile.setAcceptTime(asnDetails.get(i).getAcceptTime());
            asnDetailFile.setState(asnDetails.get(i).getState());
            asnDetailFile.setAsnUdfDs1(asnDetails.get(i).getAsnUdfDs1());
            asnDetailFile.setAsnUdfDs2(asnDetails.get(i).getAsnUdfDs2());
            asnDetailFile.setAsnUdfDs3(asnDetails.get(i).getAsnUdfDs3());

            asnDetailFileService.save(asnDetailFile);


        }
        asnMasterService.deleteByBillNo(billNo);
        BillRecord billRecord1 = billRecordService.findByBillNoAndType(billNo,6);//ASN归档
        billRecord1.setModifyUserId(fileUserId);
        billRecord1.setModifyUserName(fileUserName);
        billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
        billRecordService.updateById(billRecord1);
    }

    @Override
    public void createASN(CreateASN createASN, CurrentUser currentUser) {
        AsnMaster asnMaster = new AsnMaster();
        String tableName = "asn_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo =createASN.getBillNo();
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();

        String wareCode = createASN.getWareCode();
        String orgCode = createASN.getOrgCode();
        WareInfo wareInfo = wareInfoService.getOneByField("ware_code",wareCode);

        Organization organization = organizationService.findBy("organization_code",orgCode);

        asnMaster.setAsnState(0);
        asnMaster.setBillNo(billNo);
        asnMaster.setCreateUserId(createUserId);
        asnMaster.setCreateUserName(createUserName);
        asnMaster.setWareId(wareInfo.getWareId());
        asnMaster.setWareName(wareInfo.getWareName());
        asnMaster.setWareId(wareInfo.getWareId());
        asnMaster.setWareCode(wareInfo.getWareCode());
        asnMaster.setOrganizationCode(organization.getOrganizationCode());
        asnMaster.setOrganizationName(organization.getOrganizationName());
        asnMaster.setOrganizationId(organization.getOrganizationId());
        asnMaster.setRequestBuyBillNo(createASN.getBillNo());
        asnMaster.setInsertType(4);
        asnMasterService.save(asnMaster);
        List<CreateASNShipDetail> shipDetails = createASN.getShipList();
        if(shipDetails!=null){
            for (CreateASNShipDetail createASNShipDetail:shipDetails
            ) {
                AsnShipDetail asnShipDetail = asnShipDetailService.findBy("ship_bill_code",createASNShipDetail.getShipBillCode());
                if(asnShipDetail==null){
                    asnShipDetail = new AsnShipDetail();
                    asnShipDetail.setBillNo(asnMaster.getBillNo());
                    asnShipDetail.setShipBillCode(createASNShipDetail.getShipBillCode());
                    asnShipDetail.setShipCode(createASNShipDetail.getShipCode());
                    asnShipDetailService.save(asnShipDetail);
                }else {

                }
            }
        }
        List<CreateASNSKUDetail> asnskuDetails = createASN.getSkuList();
        for(int i = 0;i<asnskuDetails.size();i++){
            CreateASNSKUDetail  createASNSKUDetail = asnskuDetails.get(i);

            ItemInfo itemInfo = itemInfoService.findBy("item_code",createASNSKUDetail.getSkuCode());
            if(itemInfo==null){
                itemInfo = new ItemInfo();
                itemInfo.setItemCode(createASNSKUDetail.getSkuCode());
                itemInfo.setItemName(createASNSKUDetail.getSkuName());
                itemInfo.setImgUrl(createASNSKUDetail.getImgUrl());
                itemInfo.setOrganizationId(organization.getOrganizationId());
                itemInfo.setPackCode("sys_pack");
                itemInfoService.save(itemInfo);
            }else if(itemInfo.getImgUrl()==null || itemInfo.getImgUrl().equals("")   ){
                itemInfo.setImgUrl(createASNSKUDetail.getImgUrl());
                itemInfoService.updateById(itemInfo);
            }
            AsnDetail asnDetail = new AsnDetail();
            asnDetail.setBillNo(asnMaster.getBillNo());
            asnDetail.setDetailNo(asnMaster.getBillNo()+(i+1));
            asnDetail.setItemCode(createASNSKUDetail.getSkuCode());
            asnDetail.setItemName(createASNSKUDetail.getSkuName());
            asnDetail.setSpec(createASNSKUDetail.getSpec());
            asnDetail.setModel(createASNSKUDetail.getModel());
            asnDetail.setImgUrl(createASNSKUDetail.getImgUrl());
            asnDetail.setPackCode("sys_pack");
            asnDetail.setPackDetailId(166);
            asnDetail.setPackDescribe("each");
            asnDetail.setTransRatio(1.0);
            asnDetail.setExpectQuantity(createASNSKUDetail.getQuantity());
            asnDetailService.save(asnDetail);

        }

    }

    @Override
    public AsnMasterDto findByBillNo(String billNo) {
        return asnMasterMapper.findByBillNo(billNo);
    }

    @Override
    public AsnMaster  findSoByBillNo( String billNo,  String wareCode) {
        return asnMasterMapper.findSoByBillNo(billNo,wareCode);
    }

    @Override
    public AsnMaster findBy(String field, String value) {
        QueryWrapper<AsnMaster> qw = new QueryWrapper<>();
        return getOne(qw.eq(field, value));
    }

    @Override
    public void savePurchaseOrder(Map<String, Object> map) {
        List<PurchaseOrderBO> po = pushErpService.GetAllIMSourceBills(map);
        List<Integer> inputBillNos = Arrays.asList(82, 251300022, 251300022, 251300058, 200000013,702,85,251300056);
        //入库任务
        List<PurchaseOrderBO> collect = po.stream().filter(item -> inputBillNos.contains(item.getBillTypeId())).collect(Collectors.toList());
        saveBathErp(collect);
        //出库任务
        List<PurchaseOrderBO> outPut = po.stream().filter(item -> !inputBillNos.contains(item.getBillTypeId())).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(outPut)) {
            return;
        }
        soDetailService.syncCurentData(outPut);

    }

    /**
     * 卓品
     * 处理从接口同步过来的ERP任务，新增或者修改
     * @param erpTaskList 处理从接口同步过来的ERP任务
     */
    public void saveBathErpForZP(List<ErpTask> erpTaskList, Integer billType) {
        if (ObjectUtil.isEmpty(erpTaskList)) {
            return;
        }
        //单号
        Map<String, List<ErpTask>> erpNoMap = new HashMap<>();
        Set<String> billNos = erpTaskList.stream().map(ErpTask::getErpNo).collect(Collectors.toSet());
        if (ObjectUtil.notEqual(ErpInConstant.ERP_IN_TYPE_PRD, billType)) {
            erpNoMap = erpTaskList.stream().collect(Collectors.groupingBy(ErpTask::getErpNo));
        } else {
            erpNoMap = erpTaskList.stream().collect(Collectors.groupingBy(ErpTask::getDocNo));
        }

        List<AsnMaster> oldAsnMasterList = asnMasterService.list(new QueryWrapper<AsnMaster>().in("bill_no", billNos));
        Map<String, AsnMaster> oldAsnMasterMap = CollectionUtils.convertMap(oldAsnMasterList, AsnMaster::getBillNo);
        Set<String> oldBillNos = oldAsnMasterList.stream().map(AsnMaster::getBillNo).collect(Collectors.toSet());

        Integer wareId = 286; //写死，卓品仓库
        WareInfo wareInfo = wareInfoService.getById(wareId);
        List<AsnDetail> asnDetails = new ArrayList<>();
        List<AsnMaster> asnMasters = new ArrayList<>();
        List<AsnDetail> updateAsnDetails = new ArrayList<>();
        List<AsnDetail> deleteAsnDetails = new ArrayList<>();
        for (String erpNo : erpNoMap.keySet()) {
            List<ErpTask> erpTasks = erpNoMap.get(erpNo);
            //判断是否已经有值
            if (!oldBillNos.contains(erpNo)) {
                //没有现成的单据，需要新建
                AsnMaster asnMaster = encapsulationErpMaster(billType, wareInfo, erpNo, erpTasks);
                for (ErpTask erpTask : erpTasks) {
                    AsnDetail asnDetail = encapsulationErpDetail(asnMaster, erpTask);
                    asnDetails.add(asnDetail);
                }
                asnMasters.add(asnMaster);
            } else {
                //已存在单据
                AsnMaster asnMaster = oldAsnMasterMap.get(erpNo);
                //可能需要更新行
                List<AsnDetail> oldAsnDetails = asnDetailService.getListByField("bill_no", erpNo);
                Map<String, AsnDetail> oldAsnDetailMap = CollectionUtils.convertMap(oldAsnDetails, AsnDetail::getDetailNo);
                Set<Integer> oldErpLineSet = CollectionUtils.convertSet(oldAsnDetails, AsnDetail::getErpLineNo);

                for (ErpTask erpTask : erpTasks) {
                    AsnDetail asnDetail = oldAsnDetailMap.get(erpNo + "-" + erpTask.getErpLineNo());
                    if (asnDetail == null) {
                        //不存在 新增
                        AsnDetail newAsnDetail = encapsulationErpDetail(asnMaster, erpTask);
                        asnDetails.add(newAsnDetail);
                    } else {
                        //修改
                        //只允许修改
                        Double erpQty = erpTask.getQty(); //采购的不能通过数量去判断
                        if (ObjectUtil.equal(ErpInConstant.ERP_IN_TYPE_PRDRETURN, asnMaster.getAsnType())
                            || ObjectUtil.equal(ErpInConstant.ERP_IN_TYPE_OSRETURN, asnMaster.getAsnType())) {
                            //销售退料
                            erpQty = erpTask.getQtyTrans();
                        }
                        if (ObjectUtil.equals(ErpInConstant.ERP_IN_TYPE_OUTSOURCE, asnMaster.getAsnType())) {
                            //委外收货
                            erpQty = erpTask.getArriveQty();
                        }
                        if (ObjectUtil.equals(ErpInConstant.ERP_IN_TYPE_PRD, asnMaster.getAsnType())) {
                            //生产完工入库
                            erpQty = erpTask.getRcvQtyByProductUom();
                        }

                        if (ObjectUtil.notEqual(erpQty, asnDetail.getExpectQuantity())) {
                            if (asnDetail.getAcceptQuantity() <= erpQty) {
                                asnDetail.setExpectQuantity(erpQty);
                                updateAsnDetails.add(asnDetail);
                            }
                        }
                    }

                    //删除
                    oldErpLineSet.remove(erpTask.getErpLineNo());
                }

                for (Integer erpLine : oldErpLineSet) {
                    AsnDetail asnDetail = oldAsnDetailMap.get(erpNo + "-" + erpLine);
                    asnDetail.setState(AsnManageConstant.ASN_STATE_CLOSE);
                    deleteAsnDetails.add(asnDetail);
                }
            }
        }

        asnMasterService.saveBatch(asnMasters);
        asnDetailService.saveBatch(asnDetails);
        asnDetailService.updateBatchById(updateAsnDetails);
        asnDetailService.updateBatchById(deleteAsnDetails);
    }

    private AsnMaster encapsulationErpMaster(Integer billType, WareInfo wareInfo, String erpNo, List<ErpTask> erpTasks) {
        //新增
        AsnMaster asnMaster = new AsnMaster();
        //仓库id
        asnMaster.setWareId(wareInfo.getWareId()); //仓库id
        asnMaster.setWareCode(wareInfo.getWareCode()); //仓库编码
        asnMaster.setWareName(wareInfo.getWareName()); //仓库名称
        asnMaster.setOrganizationId(-1);
        asnMaster.setOrganizationName("自有");
        asnMaster.setOrganizationCode("SYS_MINE");
        asnMaster.setBillSource(0);
        asnMaster.setAsnType(billType);
        asnMaster.setBillNo(erpNo);//单据编号
        asnMaster.setRequestBuyBillNo(erpTasks.get(0).getSrcDocNo());
        asnMaster.setExpectTime(erpTasks.get(0).getMakeDate());//单据日期
        asnMaster.setCreateUserName(StringUtils.isNotEmpty(erpTasks.get(0).getMakeEmpName()) ? erpTasks.get(0).getMakeEmpName() : erpTasks.get(0).getMakeEmpNo());
        asnMaster.setAsnState(0);//单据状态
        if (StringUtils.isNotEmpty(erpTasks.get(0).getSupplyCode())) {
            SupplierManage supplier = supplierManageService.getOneByField("supplier_code", erpTasks.get(0).getSupplyCode());
            if (ObjectUtil.isNull(supplier)) {
//                asnMaster.setSupplierCode(erpTasks.get(0).getSupplyCode());
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "存在供应商不存在WMS，请先同步");
            } else {
                asnMaster.setSupplierId(supplier.getSupplierId());//供应商ID
                asnMaster.setSupplierCode(supplier.getSupplierCode());
                asnMaster.setSupplierName(supplier.getSupplierName());//供应商名称
            }
        }
        return asnMaster;
    }

    private AsnDetail encapsulationErpDetail(AsnMaster asnMaster, ErpTask erpTask) {
        AsnDetail asnDetail = new AsnDetail();
        asnDetail.setBillNo(asnMaster.getBillNo());//ASN单号
        asnDetail.setPackDetailId(167);//基本单位ID
        asnDetail.setPackDescribe("PCS");//单位
        asnDetail.setTransRatio(1.0);
        asnDetail.setDetailNo(asnMaster.getBillNo()+"-"+ erpTask.getErpLineNo());//asn详情单号
        asnDetail.setDocumentId(erpTask.getId());//单据ID
        asnDetail.setLine(erpTask.getLine());//ASN单行ID
        asnDetail.setErpLineNo(erpTask.getErpLineNo());//ASN单行号
        asnDetail.setShipLineNo(erpTask.getShipLineNo());
        asnDetail.setCreateTime(getStringLocalDateTime(erpTask.getMakeDate()));//制单时间
        asnDetail.setMakeEmpNo(erpTask.getMakeEmpNo());//制单员工号
        asnDetail.setWldwNo(erpTask.getWldwNo());//客户编码
        asnDetail.setSupplierCode(erpTask.getSupplyCode());//供应商编码
        //物料编码可能不存在
        ItemInfo itemInfo = itemInfoService.getOneByField("item_code", erpTask.getItemCode());
        if (itemInfo == null) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "存在新物料，请先同步物料");
        }
        asnDetail.setItemCode(itemInfo.getItemCode());//物料编码
        asnDetail.setItemName(itemInfo.getItemName());//物料名称
        asnDetail.setExpectQuantity(erpTask.getQty());//采购数量
        if (ObjectUtil.equal(ErpInConstant.ERP_IN_TYPE_PRDRETURN, asnMaster.getAsnType()) || ObjectUtil.equal(ErpInConstant.ERP_IN_TYPE_OSRETURN, asnMaster.getAsnType())) {
            //生产退料（线边仓） //委外退料（委外仓）
            asnDetail.setExpectQuantity(erpTask.getQtyTrans());
        }
        if (ObjectUtil.equal(ErpInConstant.ERP_IN_TYPE_ASN, asnMaster.getAsnType())) {
            //采购
            asnDetail.setExpectQuantity(erpTask.getQty() - erpTask.getRcvQtyTU());
        }
        if (ObjectUtil.equals(ErpInConstant.ERP_IN_TYPE_OUTSOURCE, asnMaster.getAsnType())) {
            //委外收货
            asnDetail.setExpectQuantity(erpTask.getArriveQty());
        }
        if (ObjectUtil.equals(ErpInConstant.ERP_IN_TYPE_PRD, asnMaster.getAsnType())) {
            //生产完工入库
            asnDetail.setExpectQuantity(erpTask.getRcvQtyByProductUom());
            asnDetail.setLotNo(erpTask.getLotCode());
        }
        asnDetail.setUnitName(erpTask.getUnitName());//采购单位
        asnDetail.setSrcDocLine(erpTask.getSrcDocLine());//来源采购单据号
        asnDetail.setSrcDocLineNo(erpTask.getSrcDocLineNo());//来源采购订单据行号

        if (ObjectUtil.isNotNull(erpTask.getTypeNo())) {
            asnDetail.setIssueType(Integer.parseInt(erpTask.getTypeNo()));//领料单类别( 0 生产领料 , 1 生产退料 , 默认 0 )
        }
        asnDetail.setMo(erpTask.getMo());//生产订单ID
        asnDetail.setMoPick(erpTask.getMoPick());//生产订单备料ID

        asnDetail.setStatus(erpTask.getStatus());//状态
        asnDetail.setOrg(erpTask.getOrg()+"");//组织ID
        asnDetail.setState(0);

        return asnDetail;
    }

    public void saveBathErp(List<PurchaseOrderBO> po) {
        if (ObjectUtil.isEmpty(po)) {
            return;
        }
        //单号
        Set<String> billNos = po.stream().map(PurchaseOrderBO::getBillNo).collect(Collectors.toSet());
        List<AsnMaster> oldAsnMaster = asnMasterService.list(new QueryWrapper<AsnMaster>().in("bill_no", billNos));

//        this.updateOrder(oldAsnMaster, po);

        Map<String, AsnMaster> asnMap = oldAsnMaster.stream().collect(Collectors.toMap(AsnMaster::getBillNo, asnMaster -> asnMaster, (oldValue, newValue) -> newValue));
        if (ObjectUtil.isNotEmpty(po)) {
            Integer wareId = 1;
            List<WareInfo> wareInfoList = wareInfoService.list();
            Map<Integer, WareInfo> wareMap = wareInfoList.stream().collect(Collectors.toMap(WareInfo::getWareId, item -> item, (oldValue, newValue) -> newValue));
            List<AsnDetail> asnDetails = new ArrayList<>();
            List<AsnMaster> asnMasters = new ArrayList<>();
            List<ItemInfo> itemInfos = new ArrayList<>();
            for (PurchaseOrderBO bo : po) {
                if (ObjectUtil.isEmpty(asnMap.get(bo.getBillNo()))) {
                    AsnMaster asnMaster = new AsnMaster();
                    //仓库id
                    asnMaster.setWareId(wareId); //仓库id
                    asnMaster.setWareCode(wareMap.get(wareId).getWareCode()); //仓库编码
                    asnMaster.setWareName(wareMap.get(wareId).getWareName()); //仓库名称
                    asnMaster.setOrganizationId(-1);
                    asnMaster.setOrganizationName("自有");
                    asnMaster.setOrganizationCode("SYS_MINE");
                    asnMaster.setBillSource(0);
                    asnMaster.setBeforeNum(bo.getId()); //源单id
                    asnMaster.setBillType(bo.getBillTypeId());//单据类型ID
                    asnMaster.setUda1(bo.getBillTypeName());//单据类型
                    asnMaster.setBillNo(bo.getBillNo());//单据编号
                    asnMaster.setExpectTime(bo.getBillDate());//单据日期
                    asnMaster.setAsnState(0);//工业单据状态
                    asnMaster.setSupplierId(bo.getSupplierId());//供应商ID
                    asnMaster.setSupplierName(bo.getSupplierName());//供应商名称
                    asnMaster.setCreateUserId(bo.getCustomerId());//客户ID
                    asnMaster.setAsnUdfHs2(bo.getCustomerName());//客户名称
                    asnMaster.setUda3(bo.getDeptName());//部门名称
                    asnMaster.setMemo(bo.getRemark());//备注
                    asnMaster.setAgreementNo(bo.getDetails().iterator().next().getAgreementNo()); //履约号
                    asnMaster.setAsnType(bo.getDetails().iterator().next().getTargetBillTypeId()); //入库单类型1,2,5,10,41
                    List<PurchaseOrderDetailBO> purchaseOrderDetailBOS = bo.getDetails();
                    Integer i = 1;
                    for (PurchaseOrderDetailBO purchaseOrderDetailBO : purchaseOrderDetailBOS) {
                        AsnDetail asnDetail = new AsnDetail();
                        asnDetail.setBillNo(asnMaster.getBillNo());//ASN单号
                        asnDetail.setPackDetailId(33469);//基本单位ID
                        asnDetail.setPackDescribe(purchaseOrderDetailBO.getUnitName());//单位
                        asnDetail.setExpectPackDetailId(purchaseOrderDetailBO.getItemId());//物料ID
                        asnDetail.setItemCode(purchaseOrderDetailBO.getItemNumber());//物料编码
                        asnDetail.setItemName(purchaseOrderDetailBO.getItemName());//物料名称
                        asnDetail.setDocumentId(Convert.toLong(bo.getId()));
                        asnDetail.setUda1(purchaseOrderDetailBO.getItemModel());//规格型号
                        asnDetail.setAcceptPackDetailId(purchaseOrderDetailBO.getAuxPropClassId());//辅助属性类别ID
                        asnDetail.setUpperPackDetailId(purchaseOrderDetailBO.getAuxPropId());//辅助属性ID
                        asnDetail.setAsnUdfDs1(purchaseOrderDetailBO.getAuxPropName());//辅助属性
                        asnDetail.setDetailNo(asnMaster.getBillNo() + "-" + i);
                        asnDetail.setStockId(purchaseOrderDetailBO.getStockId());  //仓库id
                        asnDetail.setMemo(purchaseOrderDetailBO.getRemark());
                        asnDetail.setUda2(purchaseOrderDetailBO.getBatchManager() == null || purchaseOrderDetailBO.getBatchManager() == false ? "0" : "1");
                        asnDetail.setErpBatch(purchaseOrderDetailBO.getBatchNo());//批号
                        if (bo.getBillTypeId() == 702) {
                            asnDetail.setExpectQuantity(purchaseOrderDetailBO.getQcQty());//待检数量,为全部数量
                            ItemInfo itemInfo = itemInfoService.getOneByField("item_code", purchaseOrderDetailBO.getItemNumber());
                            if (ObjectUtil.isNotNull(itemInfo) && !"SYS-CHECK".equals(itemInfo.getQcTacticCode())) {
                                itemInfo.setQcTacticCode("SYS-CHECK");
                                itemInfos.add(itemInfo);
                            }
                        } else {
                            asnDetail.setExpectQuantity(purchaseOrderDetailBO.getQty());//基本单位数量
                            asnDetail.setAcceptQuantity(purchaseOrderDetailBO.getQcQty());//基本单位待检数量
                        }
                        asnDetail.setErpLineNo(purchaseOrderDetailBO.getRowIndex());//行号

                        asnDetail.setPackCode(purchaseOrderDetailBO.getMtoNo());//计划跟踪号

                        //目标单据红蓝字
                        asnDetail.setExpectPackDescribe(purchaseOrderDetailBO.getTargetBillROB() == null || purchaseOrderDetailBO.getBatchManager() == false ? "0" : "1");
                        asnDetail.setUpperPackDescribe(purchaseOrderDetailBO.getTargetBillTypeId().toString());
                        asnDetail.setAcceptPackDescribe(purchaseOrderDetailBO.getShelfLifeManager() == null || purchaseOrderDetailBO.getShelfLifeManager() == false ? "0" : "1");
                        asnDetail.setAsnUdfDs2(purchaseOrderDetailBO.getProductionDate());

                        i++;
                        asnDetails.add(asnDetail);
                    }
                    asnMasters.add(asnMaster);
                }

            }
            Set<String> detailNos = asnDetails.stream().map(item -> item.getDetailNo()).collect(Collectors.toSet());
            if (ObjectUtil.isEmpty(detailNos)) {
                return;
            }
            List<AsnDetail> oldDetailS = asnDetailService.list(new QueryWrapper<AsnDetail>().in("detail_no", detailNos));
            Set<String> oldDetailNos = oldDetailS.stream().map(item -> item.getDetailNo()).collect(Collectors.toSet());

            List<AsnDetail> asnDetailList = asnDetails.stream().filter(item -> !oldDetailNos.contains(item.getDetailNo())).collect(Collectors.toList());

            asnMasterService.saveBatch(asnMasters);

            asnDetailService.saveBatch(asnDetailList);

            if (itemInfos.size() != 0) {
                itemInfoService.saveOrUpdateBatch(itemInfos);
            }
        }
    }

    @Override
    public void createAsnMaster2(AsnData asnData, CurrentUser currentUser) {
        AsnMaster asnMaster = asnData.getAsnMaster();
        String tableName = "asn_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo = "ASN"+"-"+nextId;
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        //0-等待审核 1-审核通过 -1-审核退回
        Integer state = 2;

        //调拨生成
        if(asnData.getBillSource()==4){
            BillRecord billRecord2 =billRecordService.findByBillNoAndType(asnMaster.getAllotBillNo(),41);//生成ASN

            billRecordService.updateBillRecord(billRecord2,currentUser);
        }
        //采购生成
        if(asnData.getBillSource()==0 ||asnData.getBillSource()==2 ){
            BillRecord billRecord2 =billRecordService.findByBillNoAndType(asnMaster.getRequestBuyBillNo(),10);//生成ASN
            billRecordService.updateBillRecord(billRecord2,currentUser);
        }

        //新增Master
        asnMaster.setCreateUserId(createUserId);
        asnMaster.setCreateUserName(createUserName);
        asnMaster.setState(state);
        asnMaster.setInsertType(asnData.getInsertType());
        asnMaster.setBillSource(asnData.getBillSource());
        asnMaster.setAsnUdfHs1("1");//标记先发配件入库任务字段
        if (StringUtils.isNotEmpty(asnMaster.getBillNo())) {
            asnMasterService.updateById(asnMaster);
        } else {
            asnMaster.setBillNo(billNo);
            asnMasterService.save(asnMaster);
        }


        //新增detail
        List<AsnDetail> asnDetails = asnData.getAsnDetails();
        for (int i = 0; i < asnDetails.size(); i++) {
            String detailNo = billNo + "-" + (i + 1);
            AsnDetail asnDetail = asnDetails.get(i);
            asnDetail.setBillNo(billNo);
            asnDetail.setId(null);
            asnDetail.setDetailNo(detailNo);
            asnDetailService.save(asnDetail);
            //更新采购单的ASN数量
            String requestDetailDetailNo = asnDetail.getRequestDetailDetailNo();
            RequestBuyDetail requestBuyDetail = requestBuyDetailService.findByDetailNo(requestDetailDetailNo);
            if (requestBuyDetail != null) {
                requestBuyDetail.setAsnQuantity(asnDetail.getExpectQuantity() + requestBuyDetail.getAsnQuantity());
                requestBuyDetailService.updateById(requestBuyDetail);
            }
        }
    }

    @Override
    public List<AsnMasterDto> findList2(AsnMasterCriteria criteria) {
        return asnMasterMapper.findList2(criteria);
    }

    @Override
    public List<AsnMasterDto> findQcList(AsnMasterCriteria criteria) {
        return asnMasterMapper.findQcList(criteria);
    }

    @Override
    public void updateQcState(String billNo, int qcState) {
        asnMasterMapper.updateQcState(billNo,qcState);
    }

    /**
     * 出库单据到入库
     *
     * @param
     */
    @Override
    public void saveOrder(List<BillOutBO> boList) {
        List<PurchaseOrderBO> po = new ArrayList<>();
        boList.forEach(item->{
            PurchaseOrderBO purchaseOrderBO = new PurchaseOrderBO();
            BeanUtils.copyProperties(item, purchaseOrderBO);
            List<BillOutDetailBO> details = item.getDetails();
            List<PurchaseOrderDetailBO> detailBOS = new ArrayList<>();
            for (BillOutDetailBO detail : details) {
                PurchaseOrderDetailBO purchaseOrderDetailBO = new PurchaseOrderDetailBO();
                BeanUtils.copyProperties(detail, purchaseOrderDetailBO);
                detailBOS.add(purchaseOrderDetailBO);
            }
            purchaseOrderBO.setDetails(detailBOS);
            po.add(purchaseOrderBO);
        });
        saveBathErp(po);

    }

    /**
     * 回传ERP事务
     *
     * @param asnMaster
     * @param cellCode
     * @param currentUser
     */
    @Override
    public void accomplish(AsnMaster asnMaster, String cellCode, CurrentUser currentUser) {
        //step0上架指定货位
        acceptRecordService.createByAsnDetail(asnMaster,cellCode,currentUser);

    }


    @Autowired
    private ErpService erpService;

    /**
     * asn通知单查询
     * @param hashMap 条件
     */
    @Override
    public void addAsnNoticeOf(Map<String, String> hashMap) {
        List<ErpTask> asnNotices = new ArrayList<>();
        //查询条件
        hashMap.put("status", "2");
        if (StringUtils.isEmpty(hashMap.get("erpNo"))) {
            hashMap.put("makeDate", ErpInConstant.SYNC_DATA);  //期初时间   2022-09-01
        }
        //查询单据类型集合
        List<DataDictDetail> details=dataDictDetailService.findBydDataDictCode("erpTypeCode");
        for(DataDictDetail data:details){
            hashMap.put("erpTypeCode", data.getDictValue());
            asnNotices.addAll(erpService.queryAsnNoticeOf(hashMap));
        }
        //查询获取到的数据
//        hashMap.put("erpTypeCode", "PO01");
//        asnNotices.addAll(erpService.queryAsnNoticeOf(hashMap));
//        //FIXME : 临时方案
//        hashMap.put("erpTypeCode", "PO22");
//        asnNotices.addAll(erpService.queryAsnNoticeOf(hashMap));
//        hashMap.put("erpTypeCode", "PO23");
//        asnNotices.addAll(erpService.queryAsnNoticeOf(hashMap));
        //期初要拉取还没有执行完的单子
        List<ErpTask> collect = asnNotices.stream().filter(erpTask -> (erpTask.getQty() - erpTask.getRcvQtyTU()) > 0).collect(Collectors.toList());
//        System.out.println(collect.size());
        this.saveBathErpForZP(collect, ErpInConstant.ERP_IN_TYPE_ASN);
    }

    /**
     * 字符串转LocalDateTime
     * @param str 时间字符串
     * @return
     */
    public LocalDateTime getStringLocalDateTime(String str){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(str.replace('T',' '), formatter);
        return dateTime;
    }

    public boolean equal(double a, double b) {
        if ((a- b> -0.000001) && (a- b) < 0.000001)
            return true;
        else
            return false;
    }

    /**
     * 销售退货申请单查询接口
     * @param hashMap 条件
     */
    @Override
    public void addSalesReturn(Map<String, Object> hashMap) {
        hashMap.put("status", 3);
        hashMap.put("makeDate", ErpInConstant.SYNC_DATA); //
        //获取销售退货申请单查询数据
        List<ErpTask> erpTasks = erpService.salesReturnApplication(hashMap);
//        System.out.println(erpTasks.size());
        this.saveBathErpForZP(erpTasks, ErpInConstant.ERP_IN_TYPE_SALESRETURN);
    }

    /**
     * 生产退料申请单查询接口
     * @param hashMap 条件
     */
    @Override
    public void addProductionMaterialReturn(Map<String, Object> hashMap) {
        hashMap.put("makeDate", ErpInConstant.SYNC_DATA);
        hashMap.put("status", 2); //查询已审核的调拨单，调拨类型是TransIn005
        hashMap.put("docType", "TransIn002");
        hashMap.put("transOutWh", "ZP05");
        //生产退料申请单接口
        List<ErpTask> erpTasks = erpService.productionMaterialReturnApplication(hashMap);
//        System.out.println(erpTasks.size());
        this.saveBathErpForZP(erpTasks, ErpInConstant.ERP_IN_TYPE_PRDRETURN);
    }

    /**
     * 生产订单完工查询接口
     * @param hashMap 条件
     */
    @Override
    public void addCompletionProductionOrder(Map<String, Object> hashMap) {
        hashMap.put("makeDate", ErpInConstant.SYNC_DATA); //
        hashMap.put("status", 3); //查询已审核的调拨单，调拨类型是TransIn005
        List<ErpTask> erpTasks = erpService.completionOfTheReportApplication(hashMap);
        this.saveBathErpForZP(erpTasks, ErpInConstant.ERP_IN_TYPE_PRD);
    }

    /**
     * 委外退料
     * @param hashMap
     */
    @Override
    public void getOutSourceBillNo(Map<String, Object> hashMap) {
        hashMap.put("makeDate", ErpInConstant.SYNC_DATA);
        hashMap.put("status", 2); //查询已审核的调拨单，调拨类型是TransIn005
        hashMap.put("docType", "TransIn005");
        List<ErpTask> erpTasks = erpService.getOutSourceBillNo(hashMap);
//        System.out.println(erpTasks.size());
        this.saveBathErpForZP(erpTasks, ErpInConstant.ERP_IN_TYPE_OSRETURN);
    }

    /**
     * 委外收货
     * @param hashMap
     */
    @Override
    public void queryOtherIn(Map<String, Object> hashMap) {
        hashMap.put("status", 5);  //拉取的是已关闭的任务
        hashMap.put("makeDate", ErpInConstant.SYNC_DATA);
        hashMap.put("docType", "RCV11");
        List<ErpTask> erpTasks = erpService.queryOtherIn(hashMap);
        List<ErpTask> collect = erpTasks.stream().filter(erpTask -> erpTask.getWhCode().equals("ZP01") || erpTask.getWhCode().equals("ZP04")).collect(Collectors.toList());
        this.saveBathErpForZP(collect, ErpInConstant.ERP_IN_TYPE_OUTSOURCE);
    }

    @Override
    public void saveInTaskByERP(Map<String, String> hashMap) {

    }

    @Override
    public void updateErp(AsnMaster asnMaster) {
        String billNo = asnMaster.getBillNo();
        //1.删除老单子
        List<AsnDetail> oldDetails = asnDetailService.getListByField("bill_no", asnMaster.getBillNo());
        for (AsnDetail oldDetail : oldDetails) {
            asnDetailService.removeById(oldDetail);
        }
        asnMasterService.removeById(asnMaster);

        //2.拉新最新的单子
        //查询条件
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("status", "2");
        hashMap.put("erpNo", billNo);
        hashMap.put("erpTypeCode", "PO01");
        //查询获取到的数据
        List<ErpTask> asnNotices = erpService.queryAsnNoticeOf(hashMap);
        //期初要拉取还没有执行完的单子
        List<ErpTask> collect = asnNotices.stream().filter(erpTask -> (erpTask.getQty() - erpTask.getRcvQtyTU()) > 0).collect(Collectors.toList());
        this.saveBathErpForZP(collect, ErpInConstant.ERP_IN_TYPE_ASN);
    }

    /**
     * 添加回传日志信息
     * @param returnMap
     */
    public void erpLog(Map<String,Object> returnMap,int type){
        //添加回传日志信息
        ErpBackRecord erpBackRecord = new ErpBackRecord();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String tim = df.format(new Date());
        erpBackRecord.setCreateTime(tim);
        erpBackRecord.setParam(returnMap.get("result").toString());
        erpBackRecord.setMsg(returnMap.get("msg").toString());
        erpBackRecord.setCode(returnMap.get("code").toString());
        erpBackRecord.setType(type+"");
        erpBackRecordMapper.insert(erpBackRecord);
    }

    /**
     * 调用第三方接口
     * @param pathUrl 地址
     * @param data    参数
     * @return
     */
    public static Map<String,Object> doPostOrGet(String pathUrl, String data){
        System.out.println("=================================================");
        System.out.println(data);
        System.out.println("=================================================");
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        Map<String, Object> map = new HashMap<>();
        try {
            URL url = new URL(pathUrl);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("POST");
            //conn.setRequestMethod("GET");

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            conn.setDoOutput(true);
            conn.setDoInput(true);

            /**
             * 下面的三句代码，就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();

            /**
             * 下面的代码相当于，获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            map = JSON.parseObject(result);
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}

